package logmgr;

import static Common.ByteArray.* ;
import Common.GoggleDB;
import storage.data.Page;
import storage.data.PageID;


public class StringRecord extends LogMgr {
	public String old, cur ;
	
	public void redo (){ 
//		System.out.printf ( "REDO transaction:%d page:%d offset:%d from the value:%d to value:%d\n",
//		txnum, pageid,  pos, (Integer)old, (Integer)cur ) ;
		try {
			PageID pid = new PageID ( pageid ) ;
			Page aPage = new Page () ; 
			GoggleDB.bufferMgr.pinPage(pid, aPage, false) ;
			writeString ( aPage.getData(), pos,  cur ) ;
			GoggleDB.bufferMgr.unpinPage(pid, true ) ;
			GoggleDB.bufferMgr.flush( pid ) ;
		}catch ( Exception e ) {
		}
		
	} 
	
	public void undo () {
//		System.out.printf ( "UNDO transaction:%d page:%d offset:%d from the value:%d to value:%d\n",
//				txnum, pageid, pos, (Integer)old, (Integer)cur ) ;		
		try {
			PageID pid = new PageID ( pageid ) ;
			Page aPage = new Page () ; 
			GoggleDB.bufferMgr.pinPage(pid, aPage, false) ;
			writeString ( aPage.getData(), pos, old ) ;
			GoggleDB.bufferMgr.unpinPage(pid, true ) ;
			GoggleDB.bufferMgr.flush( pid ) ;
		}catch ( Exception e ) {
		}
	}
	
	public void read () throws Exception {
		byte[] buff = new byte [ 4 ] ; 
		long point = file.getFilePointer() ;
		file.seek( point + 12 );
		file.read( buff ) ;
		int len1 = readInt ( buff, 0 ) ;
		file.seek( point + 16 + len1 );
		file.read( buff ) ;
		int len2 = readInt ( buff, 0 ) ;
		
		buff = new byte [ 20 + len1 + len2 ] ; 
		file.seek( point ); 
		file.read( buff ) ;
		txnum = readInt ( buff,  0 ) ;
		pageid = readInt ( buff, 4 ) ;
		pos = readInt ( buff, 8 ) ;
		old = readString ( buff, 12 ) ;
		cur = readString ( buff, 16 + len1 ) ; 
	}
	
	@Override
	public void write ( int txnum, int pageid, int pos, Object old, Object cur ) throws Exception {
		String s1 = (String)old ;
		String s2 = (String)cur ; 
		byte [] buff = new byte [ 24 + s1.length() + s2.length() ] ;
		writeInt ( buff, 0, STRING ) ;
		writeInt ( buff, 4, txnum ) ;
		writeInt ( buff, 8, pageid ) ;
		writeInt ( buff, 12, pos ) ;
		writeString ( buff, 16, s1 ) ;
		writeString ( buff, 20 + s1.length() , s2 ) ;
		file.seek( file.length() ) ;
		file.write ( buff ) ; 
	}
}
